import java.awt.Dimension;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.DecimalFormat;
import java.util.Scanner;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;


/*
 * EncryptGUI.java : Provides to hide the information
 * 					written in a texts, like in Word Document, and re-shows 
 * 					it also by decrypting
 *  @Author : BilCIS
 */

public class EncryptGUI extends JPanel
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 9152025574501401282L;	

	
	// Variables declaration	
	private JPanel contentPane;
	
	private TextArea beforeDoc;
	private TextArea afterDoc;
	private JTextArea info;
	
	private JButton encode;
	private JButton decode;
	private JButton choose;
	
	private JFileChooser chooser;
	private File file;
	
	private Scanner scan;
	
	private String fileStr;
	
	private boolean flag = false;
	private boolean flag2 = false;
	
	private Employee emp;
	// End of variables declaration
	
	// Constructor
	public EncryptGUI( Employee emp )
	{
		chooser = new JFileChooser();
		this.emp = emp;
		create();
		this.setVisible(true);
	}
	
	private void create()
	{
		//
		// Create controls
		//
		contentPane = new JPanel(null);
		beforeDoc = new TextArea("");
		afterDoc = new TextArea("");
		choose = new JButton("Choose");
		encode = new JButton("Encode");
		decode = new JButton("Decode");
		info = new JTextArea("Name:\nSize:");
		//	
		// Register action listeners
		//
		choose.addActionListener( new choose_Action() );
		encode.addActionListener( new encode_Action() );
		decode.addActionListener( new decode_Action() );
		//	
		// Mnemonics
		//
		choose.setMnemonic('c');
		encode.setMnemonic('e');
		decode.setMnemonic('d');
		//
		// Add controls to pane
		//
		this.add(contentPane);
		contentPane.add(beforeDoc);
		contentPane.add(choose);
		contentPane.add(afterDoc);
		contentPane.add(encode);
		contentPane.add(decode);
		contentPane.add(info);
		//	
		// Set bounds
		//	
		contentPane.setBounds(0,0,900,440);
		beforeDoc.setBounds(10,10,380,400);
		choose.setBounds(400,130,90,50);
		encode.setBounds(400,200,90,50);
		decode.setBounds(400,270,90,50);
		afterDoc.setBounds(500,10,380,400);
		info.setBounds(392,60,105,40);
		//
		//	Text Area
		//
		beforeDoc.setEditable(false);
		beforeDoc.setBackground(emp.getColor());
		beforeDoc.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
		
		afterDoc.setEditable(false);
		afterDoc.setBackground(emp.getColor());
		afterDoc.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
		
		info.setEditable(false);
		info.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
		
		
		//********************** Colors *********************//
		contentPane.setBackground(emp.getColor());
		
		//
		// Settings
		//	
		this.setSize(new Dimension(900, 440));
		this.setLayout(null);
	}
	
	
	public class Action implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			Object source = e.getSource();
		
			if ( source == encodeOn )
			{
				flag2 = false;
			}
			else if ( source == encodeOff )
			{
				flag2 = true;
			}
		}
	}
	
	// Buttons
	JRadioButton	encodeOn;
	JRadioButton	encodeOff;
	
	// Chooses the file and gets it
	public class choose_Action implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			beforeDoc.setText("");
			fileStr = "";
			//
			JPanel 			pane = new JPanel();
			ButtonGroup		group = new ButtonGroup();
			group.add(encodeOn);
			group.add(encodeOff);
			encodeOn = new JRadioButton("For Encode");
			encodeOff = new JRadioButton("For Decode");
			
			Action groupAc  = new Action();
			encodeOn.addActionListener(groupAc);
			encodeOff.addActionListener(groupAc);
			
			pane.add(encodeOn);
			pane.add(encodeOff);
			
			JOptionPane.showMessageDialog(null, pane);
			//
			int status = chooser.showOpenDialog(null);
			
			if(status != JFileChooser.APPROVE_OPTION)
				JOptionPane.showMessageDialog(null,"No File Chosen");
			else
			{
				file = chooser.getSelectedFile();
				flag = true;
				if ( flag2 == true )
				{
					BufferedReader br = null;
					FileInputStream is = null;
					try {
						is = new FileInputStream(file);
					} catch (FileNotFoundException e1) {
						
						e1.printStackTrace();
					}
					try {
						br = new BufferedReader(new InputStreamReader(is, "Unicode"));
					} catch (UnsupportedEncodingException e1) {
						
						e1.printStackTrace();
					}		
					String readLine = null;
					try {
						while ((readLine = br.readLine()) != null) 
						{
							fileStr += readLine + "\n";
						}
					} catch (IOException e1) {
						
						e1.printStackTrace();
					}		
					beforeDoc.setText(fileStr);
				}
				else
				{
					try {
						scan = new Scanner(file);
					} catch (FileNotFoundException e1) {
						
						e1.printStackTrace();
					}
					while ( scan.hasNext() )
						fileStr += scan.nextLine() + "\n";
					
					beforeDoc.setText(fileStr);
				}
			}
			
			double bytes = file.length();
			double kilobytes = (bytes / 1024);
			
			DecimalFormat fmt = new DecimalFormat("0.###");
			
			info.setText( "Name: " + file.getName()
					+ "\nSize:  " +  fmt.format(kilobytes) + " Kb" );
		}
	}
	
	// a method to encrypt (hide) the letters
	public String encode(String str)
	{
		// letters are replaced with some unique
		// ancient Greek and Korean alphabets
		str = str.replace(' ', '♪');
		str = str.replace('a', 'Ч');
		str = str.replace('b', 'Э');
		str = str.replace('c', 'Ш');
		str = str.replace('d', 'Ж');
		str = str.replace('e', 'ψ');
		str = str.replace('f', 'б');
		str = str.replace('g', '┘');
		str = str.replace('x', '├');
		str = str.replace('y', '┌');
		str = str.replace('z', '∑');
		str = str.replace('h', 'ζ');
		str = str.replace('p', 'θ');
		str = str.replace('o', 'Ω');
		str = str.replace('s', 'Φ');
		str = str.replace('w', 'Ρ');
		str = str.replace('v', 'δ');
		str = str.replace('1', '█');
		str = str.replace('2', '▌');
		str = str.replace('3', '▀');
		str = str.replace('4', '°');
		str = str.replace('5', '²');
		str = str.replace('6', 'Ϊ');
		str = str.replace('7', 'έ');
		str = str.replace('8', 'ό');
		str = str.replace('9', 'ϋ');
		str = str.replace('0', '░');
		str = str.replace('.', '▓');
		str = str.replace(',', '▒');
		
		return str;
	} 
	
	// a method to decrypt (reveal) the letters
	public String decode(String str)
	{
		// letters are turned up the modern form
		// of English alphabet
		str = str.replace('♪', ' ');
		str = str.replace('Ч', 'a');
		str = str.replace('Э', 'b');
		str = str.replace('Ш', 'c');
		str = str.replace('Ж', 'f');
		str = str.replace('ψ', 'e');
		str = str.replace('б', 'f');
		str = str.replace('┘', 'g');
		str = str.replace('├', 'x');
		str = str.replace('┌', 'y');
		str = str.replace('∑', 'z');
		str = str.replace('ζ', 'h');
		str = str.replace('θ', 'p');
		str = str.replace('Ω', 'o');
		str = str.replace('Φ', 's');
		str = str.replace('Ρ', 'w');
		str = str.replace('δ', 'v');
		str = str.replace('█', '1');	
		str = str.replace('▌', '2');
		str = str.replace('▀', '3');
		str = str.replace('°', '4');
		str = str.replace('²', '5');
		str = str.replace('Ϊ', '6');
		str = str.replace('έ', '7');
		str = str.replace('ό', '8');
		str = str.replace('ϋ', '9');
		str = str.replace('░', '0');
		str = str.replace('▓', '.');
		str = str.replace('▒', ',');
		
		return str;
	} 
	
	// a listener method for encoding, encodes the letters
	public class encode_Action implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			if ( flag == true )
			{
				String original = beforeDoc.getText();
				String encoded = encode(original);
				
				afterDoc.setText(encoded);	
				File file2 = null;	
		    	try {
		    	
		  	      file2 = new File("./encoded/" + file.getName().substring(0,file.getName().length()-4) + "ENCODED.txt");
		   
		  	      if (file2.createNewFile()){
		  	        System.out.println("File is created!");
		  	      }else{
		  	        System.out.println("File already exists.");
		  	      }
		   
		      	} catch (IOException e1) {
		  	      e1.printStackTrace();
		  	}
				BufferedWriter writer = null;
		        try {
		        	Writer out = new BufferedWriter(new OutputStreamWriter(
		        		    new FileOutputStream(file2), "Unicode"));
		        		try {
		        		    out.write(encoded);
		        		} finally {
		        		    out.close();
		        		}
					
		            System.err.println("ok");
		        } catch (IOException e1) {
		            System.err.println(e1);
		        } finally {
		            if (writer != null) {
		                try {
		                    writer.close();
		                } catch (IOException e1) {
		                    System.err.println(e1);
		                }
		            }
		        }
			}
		}
	}
	
	// a listener method for decoding, decodes the letters
	public class decode_Action implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			if ( flag == true )
			{
				int answer = JOptionPane.showConfirmDialog(null, "Are you sure this file is encoded before?");
				
				if ( JOptionPane.YES_OPTION == answer )
				{
					String original = beforeDoc.getText();
					String decoded = decode(original);
					
					afterDoc.setText(decoded);

					File file2 = null;
			    	try {
			    	
			  	     file2 = new File("./decoded/" + file.getName().substring(0,file.getName().length()-11) + ".txt");
			   
			  	      if (file2.createNewFile()){
			  	        System.out.println("File is created!");
			  	      }else{
			  	        System.out.println("File already exists.");
			  	      }
			   
			      	} catch (IOException e1) {
			  	      e1.printStackTrace();
			  	}
					BufferedWriter writer = null;
			        try {
			        	
			        	Writer out = new BufferedWriter(new OutputStreamWriter(
			        		    new FileOutputStream(file2), "UTF-8"));
			        		try {
			        		    out.write(decoded);
			        		} finally {
			        		    out.close();
			        		}
						
			            System.err.println("ok");
			        } catch (IOException e1) {
			            System.err.println(e1);
			        } finally {
			            if (writer != null) {
			                try {
			                    writer.close();
			                } catch (IOException e1) {
			                    System.err.println(e1);
			                }
			            }
				}
			}
			
		
				
			}
		}
	}
}
	
	
	
	
	
	
	
	
	
